package ec.edu.ups.rhc.mail;

import java.io.Serializable;
import java.util.Properties;

import javax.annotation.Resource;
import javax.ejb.MessageDriven;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDrivenContext;
import javax.inject.Inject;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import ec.edu.ups.rhc.mail.Notificacion;

@MessageDriven(mappedName="mailQueue", 
			   activationConfig =  {
				@ActivationConfigProperty(propertyName = "destination", 
						  propertyValue = "queue/test"),
	    		@ActivationConfigProperty(propertyName = "acknowledgeMode",
	    					  propertyValue = "Auto-acknowledge"),
	            @ActivationConfigProperty(propertyName = "destinationType",
	            					      propertyValue = "javax.jms.Queue")
				})
public class MessageMailListener implements MessageListener, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	//@Inject
	//private Logger log;
	//Logger log = Logger.getLogger(this.getClass().getName());
	
	@Resource
	public MessageDrivenContext mdc;
	
	@Inject 
	private Propiedad propiedades;
	
	@Resource(mappedName="java:jboss/mail/Default")
	private Session mailSession;
	
	
	@Override
	public void onMessage(Message inMessage) {
		MapMessage msg = null;

	    try {
	        if (inMessage instanceof MapMessage) {
	            msg = (MapMessage) inMessage;
	           
	            System.out.println("EMAIL LISTENER: Message received: " + msg.getString("asunto") + 
	            		" destinatarios:" + msg.getString("destinatario") + " texto:" +msg.getString("texto"));
	            
	            enviarEmail(msg.getString("asunto"), msg.getString("destinatario"), msg.getString("texto"));
	            
	        } else {
	            
	            System.out.println("Mensaje equivocado: " + inMessage.getClass().getName());	
	        }
	    } catch (JMSException e) {
	    	mdc.setRollbackOnly();
	    	e.printStackTrace();
	    } catch (Throwable te) {
	    	    	
			te.printStackTrace();
	    }
	}
	
	//envia correo
	public void enviarEmail(String asunto, String destinatario, String texto){
		
		if(mailSession == null)
            mailSession = getSession();
		
		try    {
            MimeMessage m = new MimeMessage(mailSession);
            Address from = new InternetAddress("eddybarza@gmail.com");
            Address[] to = new InternetAddress[] {new InternetAddress(destinatario)};
            m.setFrom(from);
            m.setRecipients(javax.mail.Message.RecipientType.TO, to);
            m.setSubject(asunto);
            m.setSentDate(new java.util.Date());
            texto = texto.replaceAll("\n", "<br/>");
           
            m.setContent(texto,"text/html; charset=utf-8");
            Transport.send(m);
            System.out.println("Enviado");
        }
        catch (javax.mail.MessagingException e)        {
            e.printStackTrace();
	}
		
	}
	
	public Session getSession(){        
        
	    // Sender's email ID needs to be mentioned
	    String usuario= propiedades.getPropiedad("mail.usuario");
	    String password = propiedades.getPropiedad("mail.password");

	    // Assuming you are sending email from localhost
	    String host = propiedades.getPropiedad("mail.host");

	    // Get system properties
	    Properties properties = System.getProperties();

	    // Setup mail server
	    properties.setProperty("mail.user", usuario);
	    properties.setProperty("mail.password", password);
	    properties.setProperty("mail.smtp.host", host);

	    // Get the default Session object.
	    Session session = Session.getDefaultInstance(properties);
	    return session;
	  
      }

}